<template>
  <el-card shadow="never" class="aui-card--fill">
    <div class="mod-canteens__batchordermx}">
      <el-form :inline="true" :model="topData">
        <el-form-item label="发起人">
          <span>{{ $store.state.user.realName }}</span>
        </el-form-item>
        <el-form-item label="发起时间">
          <span>{{nowDate}}</span>
        </el-form-item>
        <el-form-item label="采购食堂">
          <el-select v-model="topData.canteenId" placeholder="请选择" v-if="!readonly">
            <el-option label="新食堂" value="1198803185855877122"></el-option>
            <el-option label="老食堂" value="1067246875800000066"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购总金额">
          <el-input v-model="topData.realityMoney" placeholder="请输入金额" clearable v-if="!readonly"></el-input>
          <span v-if="readonly">{{totalPrice}}</span>
        </el-form-item>
        <el-form-item>
          <el-button @click="showImport()" v-if="!readonly">导入</el-button>
        </el-form-item>
      </el-form>
      <el-row type="flex" justify="end" v-if="!readonly">
        <el-button size="small" type="primary" @click="addItem()">新增</el-button>
      </el-row>
      <el-table
        v-loading="dataListLoading"
        :data="dataList"
        border
        @selection-change="dataListSelectionChangeHandle"
        style="width: 100%;"
      >
        <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
        <el-table-column prop="foodName" label="名称" header-align="center" align="center"></el-table-column>
        <el-table-column prop="unit" label="单位" header-align="center" align="center"></el-table-column>
        <el-table-column prop="unitPrice" label="单价" header-align="center" align="center"></el-table-column>
        <el-table-column prop="purchaseNum" label="数量" header-align="center" align="center"></el-table-column>
        <el-table-column prop="money" label="金额" header-align="center" align="center"></el-table-column>
        <el-table-column prop="purchaseTime" label="采购时间" header-align="center" align="center"></el-table-column>

        <el-table-column
          :label="$t('handle')"
          fixed="right"
          header-align="center"
          align="center"
          width="150"
          v-if="!readonly"
        >
          <template slot-scope="scope">
            <el-button size="small" @click="showUpdate(scope.row)">修改</el-button>
            <el-button size="small" type="danger" @click="delTableData(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!readonly">
        <span class="total-price">
          当前金额合计
          <span class="price">{{totalPrice}}</span>
        </span>
      </div>
      <el-pagination
        :current-page="page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="limit"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="pageSizeChangeHandle"
        @current-change="pageCurrentChangeHandle"
      ></el-pagination>
      <el-row type="flex" justify="center" v-if="!readonly">
        <el-col :span="4">
          <el-button @click="cancel()">取 消</el-button>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="save()">保 存</el-button>
        </el-col>
      </el-row>
      <!-- 弹窗, 新增 / 修改 -->
      <!-- <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update> -->
    </div>
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <el-upload
        class="upload-demo"
        drag
        :action="url"
        :on-success="uploadSucess"
        name="file"
        multiple
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="visible">
      <el-form :model="dataForm" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()">
        <el-form-item label="名称" prop="foodName">
          <el-input v-model="dataForm.foodName" placeholder="名称"></el-input>
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input v-model="dataForm.unitPrice" placeholder="单价"></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="purchaseNum">
          <el-input v-model="dataForm.purchaseNum" placeholder="数量"></el-input>
        </el-form-item>
        <el-form-item label="采购时间" prop="purchaseTime">
          <el-date-picker
            v-model="dataForm.purchaseTime"
            type="date"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
/* eslint-disable */
import mixinViewModule from "@/mixins/view-module";
import AddOrUpdate from "./batchordermx-add-or-update";
import Cookies from "js-cookie";

export default {
  mixins: [mixinViewModule],
  data() {
    return {
      nowDate: "",
      visible: false,
      readonly: false,
      totalPrice: 0,
      dataList: [],
      batchOrderDTO: {},
      url: "",
      dialogVisible: false,
      topData: {
        canteenId: "1198803185855877122"
      },
      dataForm: {
        batchOrdermxId: "",
        batchOrderId: "",
        supplierId: "",
        foodId: "",
        foodName: "",
        unit: "",
        unitPrice: "",
        purchaseNum: "",
        money: "",
        purchaseTime: "",
        entityPhoto: "",
        status: "",
        isPayment: "",
        financeId: ""
      },
      mixinViewModuleOptions: {
        getDataListURL: "canteens/batchordertem/getBatchOrdermx",
        getDataListIsPage: true,
        exportURL: "/canteens/batchordermx/export",
        deleteURL: "/canteens/batchordermx",
        deleteIsBatch: true
      },
      dataForm: {
        batchOrdermxId: ""
      }
    };
  },
  created: function() {
    this.url = `${
      window.SITE_CONFIG["apiURL"]
    }/canteens/batchordertem/excelImport?token=${Cookies.get("token")}`;
  },
  activated: function() {
    console.log(this.$route.params);
    const { add, status, batchOrderId } = this.$route.params;
    this.nowDate = this.getNowFormatDate();
    this.reverse = false;
    this.readonly = false;
    if (status === 0) {
      this.reverse = true;
      this.batchOrderId = batchOrderId;
      this.getDetails();
    } else if (status === 2) {
      this.readonly = true;
      this.batchOrderId = batchOrderId;
      this.getDetails();
    } else {
      this.getInfo();
    }
  },
  methods: {
    getNowFormatDate() {
      var date = new Date();
      var sign1 = "-";
      var sign2 = ":";
      var year = date.getFullYear(); // 年
      var month = date.getMonth() + 1; // 月
      var day = date.getDate(); // 日
      var hour = date.getHours(); // 时
      var minutes = date.getMinutes(); // 分
      var seconds = date.getSeconds(); //秒
      var weekArr = [
        "星期一",
        "星期二",
        "星期三",
        "星期四",
        "星期五",
        "星期六",
        "星期天"
      ];
      var week = weekArr[date.getDay()];
      // 给一位数数据前面加 “0”
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (day >= 0 && day <= 9) {
        day = "0" + day;
      }
      if (hour >= 0 && hour <= 9) {
        hour = "0" + hour;
      }
      if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
      }
      if (seconds >= 0 && seconds <= 9) {
        seconds = "0" + seconds;
      }
      var currentdate =
        year +
        sign1 +
        month +
        sign1 +
        day +
        " " +
        hour +
        sign2 +
        minutes +
        sign2 +
        seconds;
      return currentdate;
    },
    getInfo() {
      this.$http
        .get(`canteens/batchordertem/getBatchOrdermx`)
        .then(({ data: res }) => {
          this.dataList = res.data;
        })
        .catch(() => {});
    },
    getDetails() {
      var data = {};
      data.batchOrderId = this.batchOrderId;
      this.$http
        .post(`canteens/batchordermx/getOrdermx`, data)
        .then(({ data: res }) => {
          console.log(res.data.ordermx);
          this.dataList = res.data.ordermx;
          this.totalPrice = res.data.totalMoney;
          this.batchOrderDTO = res.data.batchOrderDTO;
          this.topData.realityMoney
        })
        .catch(() => {});
    },
    getTotal() {
      this.$http
        .get(`canteens/batchordertem/getTotalMoney`)
        .then(({ data: res }) => {
          this.totalPrice = res.data.totalMoney;
        })
        .catch(() => {});
    },
    uploadSucess(response, file, fileList) {
      if (response.code === 5000) {
        this.$message({
          message: response.data.msg,
          type: "warning"
        });
      } else {
        this.dialogVisible = false;
        this.getInfo();
        this.getTotal();
      }
    },
    delTableData(data) {
           var del = "";
      if (this.reverse) {
       
        del = "canteens/batchordermx/delete";
         data.batchOrderId = this.batchOrderId;
      } else {
        del = "canteens/batchordertem/delete";
       
      }
      this.$http
        .post(del, data)
        .then(({ data: res }) => {
            if (this.reverse) {
              this.getDetails();
            } else {
              this.getInfo();
            }
          this.getTotal();
        })
        .catch(() => {});
    },
    showUpdate(data) {
      this.visible = true;
      this.dataForm = data;
      this.addData = false;
    },
    addItem() {
      this.visible = true;
      this.addData = true;
    },
    dataFormSubmitHandle() {
      var save = "";
      var update = "";
      var data = this.dataForm
     
    
      if (this.reverse) {
        save = "canteens/batchordermx/save";
        update = "canteens/batchordermx/update";
         data.batchOrderId = this.batchOrderId;
      } else {
        save = "canteens/batchordertem/save";
        update = "canteens/batchordertem/update";
      }

      if (this.addData) {
        this.$http
          .post(save, data)
          .then(({ data: res }) => {
            this.getTotal();
            if (this.reverse) {
              this.getDetails();
            } else {
              this.getInfo();
            }
            this.visible = false;
            this.dataForm = {};
          })
          .catch(() => {});
      } else {
        this.$http
          .post(update, data)
          .then(({ data: res }) => {
            if (res.code === 5001) {
              this.$message({
                message: res.msg,
                type: "warning"
              });
            }
            if (this.reverse) {
              this.getDetails();
            } else {
              this.getInfo();
            }
            this.getTotal();
            this.visible = false;
            this.dataForm = {};
          })
          .catch(() => {});
      }
    },
    showImport() {
      this.dialogVisible = true;
    },
    handleClose() {
      this.dialogVisible = false;
    },
    cancel() {
      this.$router.push({ name: "canteens-batchorder" });
    },
    save() {
      var data = this.topData;
      data.createDate = this.nowDate;
      data.supplierId = this.$store.state.user.id;

      if (!data.canteenId) {
        this.$message({
          message: "请选择食堂",
          type: "warning"
        });

        return;
      }
      if (!data.realityMoney) {
        this.$message({
          message: "请填写采购金额",
          type: "warning"
        });

        return;
      }

      this.$http
        .post("canteens/batchorder/save", data)
        .then(({ data: res }) => {
          this.getInfo();
          this.getTotal();
          this.visible = false;
          (this.topData = {
            canteenId: "1198803185855877122"
          }),
            this.$router.push({ name: "canteens-batchorder" });
        })
        .catch(() => {});
    }
  },
  components: {
    AddOrUpdate
  }
};
</script>
<style  scoped>
.total-price {
  padding-top: 20px;
  font-size: 16px;
  line-height: 57px;
}
.total-price .price {
  color: rgb(255, 136, 0);
}
</style>
